﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QFileDialog"
#include "opencv2/opencv.hpp"
#include "QDebug"
#include "string"

using namespace cv;
int ROW,COL;
std::string filename;
unsigned char *pic;
unsigned char *buff8bit;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->Edit_w->setText("640");
    ui->Edit_h->setText("512");
    ui->Edit_bit->setText("14");
    buff8bit = (unsigned char *)malloc(ROW*COL*sizeof(char));
    pic = (unsigned char *)malloc(ROW*COL*sizeof(char)*2);
}

MainWindow::~MainWindow()
{
    free(buff8bit);
    free(pic);
    delete ui;
}

int MainWindow::getFile(unsigned char *buf,int siz)
{

    FILE * fp = NULL;
    int ret;

    fp = fopen(filename.c_str(), "r");
    if( NULL == fp ){
        return -1;
    }

    ret = fread(buf, sizeof(unsigned char), ROW*COL*siz, fp);
    if(ret < 0){
            printf("read data error!\n");
    }
    printf("The value of ret is:%d\n", ret);
    fclose(fp);
    fp = NULL;
    return 0;
}

void ytoy8(unsigned char *buf,unsigned char *buf8,int bitlen)
{
    unsigned int k = 0;
    if(bitlen == 8)
    {
        memcpy(buf8,buf,(int)ROW*COL);
        return ;
    }
    else {
        long long cf = 1;
        for(int i =0;i< (bitlen-8);i++)
        {
            cf *= 2;
        }
        for(int j = 0;j < ROW*COL*2;j+=2)
        {
            k = ((buf[j]<<8)&0xff00 | buf[j+1]&0xff);
            buf8[j/2] = k/cf;
        }
    }
}

void MainWindow::showpicture()
{
    filename = QFileDialog::getOpenFileName(this,tr("choose file")).toStdString();
    COL = ui->Edit_w->text().toInt();
    ROW = ui->Edit_h->text().toInt();
    if(COL <= 0 && ROW <= 0)
        return ;
    int datesize;
    int bitlen = ui->Edit_bit->text().toInt();
    if(8 <= bitlen <= 16)
    {
        if(bitlen == 8)
            datesize = 1;
        else {
            datesize = 2;
        }
        getFile(pic,datesize);
        qDebug()<<"hi";
        ytoy8(pic, buff8bit,bitlen);
    }
    else {
        return ;
    }
    cv::Mat tmpmat = cv::Mat(ROW,COL,CV_8UC1,pic);
    imshow("show",tmpmat);
    waitKey(0);

    return ;
}

void MainWindow::on_pushButton_clicked()
{
    showpicture();
}
